import { defineStore } from 'pinia'
import { userProfile, getSalesInfo } from "@/api/user.js";

export const useUser = defineStore('user', {
    state: () => ({
        userInfo: null,
        token: '',
        salesInfo: null
    }),
    actions: {
        setUserInfo(userInfo) {
            this.userInfo = userInfo
        },
        async setToken(token) {
            this.token = token
            await localStorage.setItem('tokenSeller', token)
            return Promise.resolve(token)
        },
        async userInfoAction() {
            try {
                const data = await userProfile({})
                this.userInfo = data.data
                localStorage.setItem('userInfoSeller', JSON.stringify(data.data))
                return Promise.resolve(data.data)
            } catch (e) {
                return Promise.reject(e.message)
            }
        },
        logoutAction() {
            localStorage.removeItem('tokenSeller')
            localStorage.removeItem('userInfoSeller')
            this.userInfo = null
            this.token = ''
        },
        async getSalesInfoAction() {
            try {
                const data = await getSalesInfo()
                this.salesInfo = data.data
                localStorage.setItem('salesInfoSeller', JSON.stringify(data.data))
                return Promise.resolve(data.data)
            } catch (e) {
                return Promise.reject(e.message)
            }
        }
    },
    getters: {
        getUserInfo: (state) => {
            try {
                const userInfo = localStorage.getItem('userInfoSeller')
                if (!state.userInfo && userInfo) {
                    state.userInfo = JSON.parse(userInfo)
                }
                return userInfo ? JSON.parse(userInfo) : state.userInfo
            } catch (error) {
                return {}
            }
        },
        getToken: (state) => {
            if (!state.token) {
                state.token = localStorage.getItem('tokenSeller')
            }
            return state.token || ''
        },
        // 根据用户好评率，返回对应的等级名称，分为1-3，3-4，5分
        getLevelName: (state) => {
            try {
                const commentRate = (state.userInfo.buyerInfo.commentRate || 0) / 10 || 0
                console.log('commentRate', commentRate, state.userInfo)
                if (commentRate >= 5) {
                    return '优秀'
                }
                if (commentRate >= 4 && commentRate < 5) {
                    return '良好'
                }
                return '一般'
            } catch (e) {
                return '无数据'
            }
        },
        getSalesInfo: (state) => {
            if (!state.salesInfo) {
                state.salesInfo = JSON.parse(localStorage.getItem('salesInfoSeller'))
            }
            return state.salesInfo || JSON.parse(localStorage.getItem('salesInfoSeller'))
        }
    },
})